package core

import (
	"lister/config"
	"net"
	"share/app"
	"share/msg"
	"util/log"
)

var (
	lister = &Lister{gateinfo: make([]msg.AppInfo, 0, 20)}
)

type Lister struct {
	appClient *app.AppClient
	servSock  *ServSock
	mquit     chan bool
	cfg       *config.Config
	runchan   chan bool
	gateinfo  []msg.AppInfo
}

func (l *Lister) Start(c *config.Config, ch chan bool) {
	l.cfg = c
	l.mquit = ch
	l.runchan = make(chan bool)
	l.initAll()
	l.run()
}

func (l *Lister) initAll() {
	l.appClient = app.CreateAppClient()
	l.servSock = CreateServSock(l.cfg.ServIp, l.cfg.ServPort)
}

func (l *Lister) run() {

	if err := l.servSock.Start(1); err != nil {
		panic("serv sock failed")
	}

	addr, _ := l.servSock.Addr().(*net.TCPAddr)

	l.appClient.Run(l.cfg.CenterIp, l.cfg.CenterPort, msg.AT_LISTER, addr.IP.String(), addr.Port)

	log.TraceInfo("lister", "service start")

loop:
	for {
		select {
		case <-l.runchan:
			break loop
		}
	}

	l.appClient.Shutdown()

	l.mquit <- true
}

func (l *Lister) shutdown() {
	l.runchan <- true
}

func GetLister() *Lister {
	return lister
}

func ServiceQuit() {
	lister.shutdown()
}
